package com.bms.common.base.common.component;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.bms.common.base.common.exception.BusinessException;
import com.bms.common.base.common.exception.EnumSvrResult;
import com.bms.common.base.common.util.JsonUtil;
import com.feilong.core.Validator;

@Component
@PropertySource({ "classpath:sms.properties" })
public class SmsUtil {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${accesskeyId}")
	private String accesskeyId;

	@Value("${accesskeySecret}")
	private String accesskeySecret;

	@Value("${signName}")
	private String signName;

	private static final String PRODUCT = "Dysmsapi";// 短信API产品名称（短信产品名固定，无需修改）
	private static final String DOMAIN = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）
	private static final String ADDRESS = "cn-hangzhou";
	/**
	 * 
	 * @param phone
	 * @param templateCode
	 *            阿里短信模块编号
	 * @param templateParam
	 *            例如：{\"code\":\"" + code + "\"} json字符串
	 * @throws ClientException 
	 * @throws BussinessException
	 */
	public void sendSms(String templateCode, Map<String,Object> templateParam,List<String> phones) throws BusinessException, ClientException {
		IClientProfile profile = DefaultProfile.getProfile(ADDRESS, accesskeyId, accesskeySecret);
		DefaultProfile.addEndpoint(ADDRESS, ADDRESS, PRODUCT, DOMAIN);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		SendSmsRequest request = new SendSmsRequest();
		request.setMethod(MethodType.POST);
		request.setPhoneNumbers(phones.toString().substring(1, phones.toString().length()-1).replaceAll(" ", ""));
		request.setSignName(signName);
		request.setTemplateCode(templateCode);
		request.setTemplateParam(JsonUtil.getJsonFromObject(templateParam));
		SendSmsResponse sendSmsResponse;
		sendSmsResponse = acsClient.getAcsResponse(request);
		logger.info("=======手机号：" + phones.toString() + ",模板：" + templateCode + ",参数:" + templateParam + ",短信发送结果======="
				+ sendSmsResponse.getCode()+"+,"+sendSmsResponse.getMessage());
		if (!Validator.isNotNullOrEmpty(sendSmsResponse.getCode()) || !sendSmsResponse.getCode().equals("OK")) {
			throw new BusinessException(EnumSvrResult.ERROR_SENG_MSG);
		}
	}
}
